// 和用户相关的状态管理
import { createSlice } from '@reduxjs/toolkit';
import { getLogin, getUserInfo } from '@/apis/user'
import { setToken as _setToken, getToken } from '@/utils';
const userStore = createSlice({
    name: 'user',
    // 数据初始化
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    // 同步修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload;
            // 本地存储一份token
            _setToken(action.payload);
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        }
    }
});
// 异步方法，完成登录获取token
const fetchLogin = (loginForm)=>{
    return async (dispatch)=>{
        // 发送异步请求
        const res = await getLogin(loginForm)
        // 提交同步Action进行token的存入
        dispatch(setToken(res.data.token))
    }
}
const fetchUserInfo = ()=>{
    return async (dispatch)=>{
        // 发送异步请求
        const res = await getUserInfo()
        // 提交同步Action进行token的存入
        dispatch(setUserInfo(res.data))
    }
}
// 解构出actionCreater
const {setToken, setUserInfo} = userStore.actions
// 获取reducer
const userReducer = userStore.reducer
export {setToken, setUserInfo, fetchLogin, fetchUserInfo}
export default userReducer;
